package com.gdzl_hadoop.util;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileUtil {
    public static File getZIP(String pathRoot, String zipName, String zipPathRoot) {
        File rootDir = new File(pathRoot);
        File zipRoot = new File(zipPathRoot);
        if (!zipRoot.exists()){
            zipRoot.mkdirs();
        }
        if (rootDir.isDirectory()) {
            File[] files = rootDir.listFiles();
            byte[] buffer = new byte[1024];
            String strZipPath = zipPathRoot + "\\" + zipName;
            try {
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
                for (int i = 0; i < files.length; i++) {
                    FileInputStream fis = new FileInputStream(files[i]);
                    out.putNextEntry(new ZipEntry(files[i].getName()));
                    out.setEncoding("GBK");
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.closeEntry();
                    fis.close();
                }
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new File(strZipPath);
        }
        return null;
    }
}
